package com.tianji.learning.service.impl;


import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisContstants;
import com.tianji.learning.domain.vo.SignResultVO;
import com.tianji.learning.mq.msg.SignInMessage;
import com.tianji.learning.service.ISignRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SignRecordServiceImpl implements ISignRecordService {

    private final StringRedisTemplate redisTemplate;
    private final RabbitMqHelper mqHelper;
    @Override
    public SignResultVO addSignRecords() {
        // 1. 获取当前用户id
        Long userId = UserContext.getUser();
        // 2. 拼接key
        LocalDate now = LocalDate.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisContstants.SIGN_RECORD_KEY_PREFIX + userId.toString() + format;

        // 3. 利用bitset命令 将签到记录保存到redis的bitmap结构中  需要校验是否已经签到
        int offset = now.getDayOfMonth() - 1;// 偏移量
        Boolean setBit = redisTemplate.opsForValue().setBit(key,offset,true);
        if(setBit){
            // 说明已经签过到了
            log.debug("{}",redisTemplate.opsForValue().get(key ));
            throw new BizIllegalException("不能重复签到");
        }
        // 4. 计算连续签到的天
        int days = countSignDays(key,now.getDayOfMonth());
        // 5. 计算连续签到奖励积分
        int rewardPoints = 0;//代表连续签到 奖励积分
        switch (days){
            case 7:
                rewardPoints = 10;
                break;
            case 14:
                rewardPoints = 20;
                break;
            case 28:
                rewardPoints = 40;
                break;
        }
//        if (days == 7){
//            rewardPoints = 10;
//        }else if(days == 14){
//            rewardPoints = 20;
//        }else if(days == 28){
//            rewardPoints = 40;
//        }

        //6. 保存积分
        mqHelper.send(MqConstants.Exchange.LEARNING_EXCHANGE,
                MqConstants.Key.SIGN_IN,
                SignInMessage.of(userId,rewardPoints+1));
        // 封装vo返回
        SignResultVO vo = new SignResultVO();
        vo.setSignDays(days);
        vo.setRewardPoints(rewardPoints);
        return vo;
    }

    /**
     * 计算连续签到多少天
     * @param key  缓存中的key
     * @param dayOfMonth   本月第一天到今天的天数
     * @return
     */
    private int countSignDays(String key, int dayOfMonth) {
        //1. 查询本月的签到数据（十进制）
        List<Long> bitField = redisTemplate.opsForValue()
                .bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands
                        .BitFieldType.unsigned(dayOfMonth)).valueAt(0));//从0开始取dayOfMonth天，结果无符号
        if (CollUtils.isEmpty(bitField)){
            return 0;
        }
        Long num = bitField.get(0);// 拿到本月的签到数据（十进制）
        log.debug("num   {}",num);
        //2. num转二进制  从后往前推共有多少1        与1做与运算（1&1=1） 右移一位
        int counter = 0;//计数器
        // 判断最后一位是否为1
        while ((num & 1) == 1){
            counter++;
            num = num>>>1;
        }
        return counter;
    }

    @Override
    public Byte[] querySignRecords() {
        // 1. 获取用户id
        Long userId = UserContext.getUser();
        // 2. 拼接 key
        LocalDate now = LocalDate.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisContstants.SIGN_RECORD_KEY_PREFIX + userId.toString() + format;

        // 3. 利用 redis 的 bitfield命令取本月第一天到今天的所有签到记录
        int dayOfMonth = now.getDayOfMonth();
        List<Long> bitField = redisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (CollUtils.isEmpty(bitField)){
            return new Byte[0];
        }
        Long num = bitField.get(0);
        int offset = dayOfMonth-1;
        // 4. 利用与运算和位移封装结构
        Byte[] arr = new Byte[dayOfMonth];
        while (offset >= 0){
            arr[offset] = (byte)(num & 1);
            num >>>= 1;
            offset--;
        }
        return arr;
    }
}
